import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_nest_life/api/home.dart';

import '../../utils/toast.dart';

class NoticeDetail extends StatefulWidget {
  const NoticeDetail({super.key});

  @override
  State<NoticeDetail> createState() => _NoticeDetailState();
}

class _NoticeDetailState extends State<NoticeDetail> {
  Map notifyDetail = {
    "id": "",
    "content": "",
    "title": "",
    "createdAt": "",
    "creatorName": ""
  };

  // @override
  // void initState() {
  //   // TODO: implement initState
  //   super.initState();
  //   getAnnounceDetail('id');
  // }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final data = ModalRoute.of(context)?.settings.arguments;
    // 将数据获取逻辑移到这里，确保路由参数已获取
    getAnnounceDetail((data as Map<String, dynamic>)['id']); // 使用动态路由参数
    print(data['id']);
  }

  // 修改为正确获取数据
  getAnnounceDetail(String id) async {
    try {
      final response = await getAnnounceDetailAPI(id);
      // 判断当前页面是否还显示在屏幕上，防止更新页面时出现错误
      if (mounted) {
        setState(() {
          notifyDetail = response; // 更新状态数据
        });
      }
    } catch (e) {
      PromptAction.showError('获取公告详情失败:$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('公告详情')),
        body: notifyDetail.isEmpty
            ? const Center(child: CircularProgressIndicator())
            : ListView(children: [
                Container(
                    padding: const EdgeInsets.all(10),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 标题
                          Text(notifyDetail['title'] ?? '',
                              style: const TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              )),
                          const SizedBox(height: 10),
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(notifyDetail['creatorName'] ?? '',
                                    style: const TextStyle(color: Colors.grey)),
                                Text(notifyDetail['createdAt'] ?? '',
                                    style: const TextStyle(color: Colors.grey))
                              ]),
                          const SizedBox(height: 10),
                          // 内容
                          Html(
                            data: notifyDetail['content'] ?? "",
                          )
                        ]))
              ]));
  }
}
